﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;

namespace tophd.Classes.Helper
{
    public class JsonHelper<T>
    {
        public string GetJsonResponse(string getMethod, Hashtable hashtable)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://vipmobi.net:7001/mobile/service?WSDL");
            httpWebRequest.ContentType = "text/xml;charset=\"utf-8\"";
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers.Add("SOAPAction", "\"\"");

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json =
                    "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:json=\"http://JsonUtils/\">" +
                    "<soapenv:Header/>" +
                    "<soapenv:Body>" +
                    "<json:" + getMethod + ">";
                foreach (DictionaryEntry hash in hashtable)
                {
                    json += "<" + hash.Key + ">" + hash.Value + "</" + hash.Key + ">";
                }
                json += "</json:" + getMethod + ">" +
                "</soapenv:Body>" +
                "</soapenv:Envelope>";
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    string result = streamReader.ReadToEnd();
                    return result;
                }
            }
        }

        public List<T> ParseJsonResponse(string json, string method)
        {
            JavaScriptSerializer ser = new JavaScriptSerializer();
            string temp =
                        json.Replace(
                            "<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"><S:Body><ns2:" + method + " xmlns:ns2=\"http://JsonUtils/\"><return xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:string\">",
                            "").Replace("</return></ns2:" + method + "></S:Body></S:Envelope>", "");
            List<T> listObj = ser.Deserialize<List<T>>(temp);
            return listObj;
        }
    }
}